<!DOCTYPE html>
<html lang='en'>

<head>
  <meta charset='UTF-8'>
  <meta http-equiv='X-UA-Compatible' content='IE=edge'>
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>
  <link rel='stylesheet' href='./layui-v2.9.10/layui/css/layui.css' media='all'>
  <link rel='stylesheet' href='./css/index.css' media='all'>
  <link rel='stylesheet' href='./css/select2.main.css' media='all'>
  <link rel="shortcut icon" type="image/x-icon" href="favicon.png" media="screen">
  <title>加强加密 - 记住一个密码等于记住无限多个密码，你值得拥有</title>
</head>

<body>
  <!-- 让 IE8/9 支持媒体查询，从而兼容栅格 -->
  <!--[if lt IE 9]>
    <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
    <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
  <![endif]-->

  <div class="link">
    <a href="https://blog.csdn.net/vieri_32/article/details/48345023">理解AES加密解密</a>
    <a href="https://www.jianshu.com/p/a47477e8126a">crypto-js加解密</a>
    <a href="https://www.cnblogs.com/wz122889488/p/6899615.html">CryptoJS加解密互转</a>
    <a href="index.html" style="color: #7d7dff;">普通加密</a>
  </div>

  <hr style="border: 1px solid #dddddd;">

  <div class="layui-row" style="display: flex; justify-content: space-around; margin: 10px;">
    <div class="layui-form-item layui-col-xs12 layui-col-sm11 layui-col-md9" style="margin: 0;">
      <form class="layui-form" lay-filter="form-body">
        <div class="layui-form-item">
          <label class="layui-form-label">key</label>
          <div class="layui-input-block">
            <input type="password" name="key" required lay-verify="required" placeholder="十六位十六进制数作为密钥"
              autocomplete="off" class="layui-input" value="">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">iv</label>
          <div class="layui-input-block">
            <input type="password" name="iv" required lay-verify="required" placeholder="十六位十六进制数作为密钥偏移量"
              autocomplete="off" class="layui-input" value="">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label "> 出生日期 </label>
          <div class="layui-input-block">
            <input type="text" id="Birthday" name="Birthday" placeholder="请输入" autocomplete="off" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label "> 毕业学校 </label>
          <div class="layui-input-block">
            <select lay-search="" id="Graduate" name='Graduate' lay-ignore> </select>
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label "> 工作地址 </label>
          <div class="layui-input-block">
            <select lay-search="" id="Work" name='Work' lay-ignore></select>
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label "> 宠物名 </label>
          <div class="layui-input-block">
            <input type="text" id="Pet" name="Pet" placeholder="请输入" autocomplete="off" class="layui-input">
          </div>
        </div>
      </form>
    </div>
  </div>

  <div class="layui-row" style="display: flex; justify-content: space-around; margin: 10px;">
    <div class="layui-tab layui-tab-card layui-col-xs12 layui-col-sm11 layui-col-md9">
      <ul class="layui-tab-title">
        <li class="layui-this">加密</li>
        <li>解密</li>
        <li id="reload" style="color: #de6868;"></li>
      </ul>
      <div class="layui-tab-content" style="padding: 0">
        <div class="layui-tab-item layui-show">
          <div class="layui-card " style="height:100%">
            <div class="layui-card-body">
              <form class="layui-form" action="">
                <div class="layui-form-item">
                  <label class="layui-form-label">密码等级</label>
                  <div class="layui-input-block">
                    <select name="grade" lay-verify="required">
                      <option value="纯数字">纯数字</option>
                      <option value="纯字母">纯字母</option>
                      <option value="数字+字母">数字+字母</option>
                      <option value="区分大小写">区分大小写</option>
                      <option value="特殊字符">特殊字符</option>
                      <option value="abc">敏感密码</option>
                    </select>
                  </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">密码</label>
                  <div class="layui-input-block">
                    <input type="text" name="password" required lay-verify="required" placeholder="请输入标题"
                      autocomplete="off" class="layui-input">
                  </div>
                </div>
                <div class="layui-form-item layui-form-text">
                  <label class="layui-form-label">密文</label>
                  <div class="layui-input-block">
                    <textarea disabled name="desc" placeholder="请输入内容" class="layui-textarea"></textarea>
                  </div>
                </div>
                <div class="layui-form-item">
                  <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
                    <button type="button" id="btnCopy" class="layui-btn layui-btn-primary cloneDesc">复制密文</button>
                  </div>
                </div>
              </form>
            </div>
          </div>
        </div>
        <div class="layui-tab-item">
          <div class="layui-card " style="height:100%">
            <div class="layui-card-body">
              <form class="layui-form" action="">
                <div class="layui-form-item layui-form-text">
                  <label class="layui-form-label">密文</label>
                  <div class="layui-input-block">
                    <textarea name="ciphertext" placeholder="请输入内容" lay-verify="required" class="layui-textarea"
                      style="height: 200px;"></textarea>
                  </div>
                </div>
                <div class="layui-form-item">
                  <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="formDemo2">立即提交</button>
                    <button type="button" class="layui-btn layui-btn-primary" id="copyPass">复制密码</button>
                  </div>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <script src="./js/crypto-js.4.0.0.js"></script>
  <script>
    // const CryptoJS = require('crypto-js');  //引用AES源码js
    // const key = CryptoJS.enc.Utf8.parse("1234123412ABCDEF");  //十六位十六进制数作为密钥      1234123412ABCDEF
    // const iv = CryptoJS.enc.Utf8.parse('ABCDEF1234123412');   //十六位十六进制数作为密钥偏移量  ABCDEF1234123412   
    var key, iv
    //解密方法
    function Decrypt(word) {
      let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
      let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
      let decrypt = CryptoJS.AES.decrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
      let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
      return decryptedStr.toString();
    }
    //加密方法
    function Encrypt(word) {
      let srcs = CryptoJS.enc.Utf8.parse(word);
      let encrypted = CryptoJS.AES.encrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
      return encrypted.ciphertext.toString().toUpperCase();
    }
  </script>

  <script src="./js/jquery.3.5.1.js"></script>
  <script src="./js/select2.main.js"></script>
  <script src="./data/address.js"></script>
  <script src="./data/universitiesData.js"></script>
  <script src='./layui-v2.9.10/layui/layui.js'></script>
  <script>

    layui.config({
      base: './modules/'
    }).extend({
      timemsg: 'timemsg', //主入口模块
    }).use(['jquery', 'form', 'laydate', 'timemsg'], function () {
      var $ = layui.jquery
      var form = layui.form
      var laydate = layui.laydate

      laydate.render({
        elem: '#Birthday'
        , type: 'date' //默认，可不填
      });

      var GraduateAddress = []
      GraduateAddress.push({ "id": '', "text": '' })
      $.each(_address_.province_list, function (key, name) {
        GraduateAddress.push({ "id": key, "text": name })
        var province_pro = (key + '').substr(0, 2);
        $.each(_address_.city_list, function (item, index) {
          if ((item + '').substr(0, 2) == province_pro) {
            GraduateAddress.push({ "id": item, "text": name + index })
            var city_pro = (item + '').substr(0, 4);
            $.each(_address_.county_list, function (countyItem, countyIndex) {
              if ((countyItem + '').substr(0, 4) == city_pro) {
                GraduateAddress.push({ "id": item, "text": name + index + countyIndex })
              }
            })
          }
        })
      })
      $("#Work").select2({
        width: '100%',
        placeholder: '请选择',
        allowClear: true, //允许清除
        maximumSelectionLength: 0,
        data: GraduateAddress,
      })

      _universities_.unshift({ "id": '', "text": '' })
      $("#Graduate").select2({
        width: '100%',
        placeholder: '请选择',
        allowClear: true, //允许清除
        maximumSelectionLength: 0,
        data: _universities_,
      })

      function genGuid() {
        //生成 网络请求 Id 
        return 'xyyxxxyx'.replace(/[xy]/g, function (c) {
          let r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
          return v.toString(16); //16进制
        });
      }

      function deleteString(str) {
        return 'x' + str.replace(/0*$/g, '') + 'y'
      }

      // 将加密后的密文和一些信息合并
      function myEncrypt(_desc) {
        var form = layui.form.val("form-body");
        var value = form.Birthday + deleteString(form.Graduate) + _desc + deleteString(form.Work) + form.Pet
        var arr = [];
        for (let i = 0; i < value.length; i++) {
          // console.log(value.charCodeAt(i))
          arr.push(value.charCodeAt(i) + value.length)
        }
        return JSON.stringify(arr)
      }

      //监听提交-加密
      form.on('submit(formDemo)', function (data) {
        if (!$('[name="key"]').val().trim() || !$('[name="iv"]').val().trim()) {
          layui.timemsg.open("输入 key 或 iv")
          return false;
        }
        try {
          if (data.field["grade"] == 'abc') data.field["grade"] = genGuid()

          var field = `${data.field["password"]},${data.field["grade"]}`;
          // layer.msg(JSON.stringify(data.field, true, 4)); 

          key = CryptoJS.enc.Utf8.parse($('[name="key"]').val())
          iv = CryptoJS.enc.Utf8.parse($('[name="iv"]').val())

          var desc = Encrypt(JSON.stringify(field))
          console.log('==', data.field, key, iv, desc)
          desc = Encrypt(myEncrypt(desc))

          // $('[name="desc"]').val(desc)
          $('[name="ciphertext"]').val($('[name="desc"]').val(desc).val())
        } catch (e) {
        }
        return false;
      });

      // 将加密后的密文和一些信息合并
      function myDecrypt(_desc) {
        var form = layui.form.val("form-body");

        var length = _desc.length;
        for (let i = 0; i < _desc.length; i++) {
          _desc[i] = _desc[i] - length
        }
        _desc = _desc = String.fromCharCode(..._desc)
        _desc = _desc.replace(form.Birthday, '')
        _desc = _desc.replace(form.Pet, '')
        _desc = _desc.replace(deleteString(form.Graduate), '')
        _desc = _desc.replace(deleteString(form.Work), '')
        return _desc;
      }

      //监听提交-解密
      form.on('submit(formDemo2)', function (data) {
        if (!$('[name="key"]').val().trim() || !$('[name="iv"]').val().trim()) {
          layui.timemsg.open("输入 key 或 iv")
          return false;
        }
        try {
          // layer.msg(JSON.stringify(data.field));
          key = CryptoJS.enc.Utf8.parse($('[name="key"]').val())
          iv = CryptoJS.enc.Utf8.parse($('[name="iv"]').val())

          var result = Decrypt(data.field.ciphertext)
          console.log('==11', result)

          result = myDecrypt(JSON.parse(result))
          result = Decrypt(result)
          console.log('==22', result, JSON.parse(result))

          var password = JSON.parse(result).split(',')

          var html = `<div id="mas" style=""> <p id="grade"> 密码等级:${password[1]}</p> <p id="password"> 密码:${password[0]}</p> </div>`
          layui.timemsg.open(html)
          window._password = password[0];
        } catch (e) {
          layui.timemsg.open("输入正确的 key/iv/密文")
        }

        return false;
      });

      $(".cloneDesc").click(function () {
        $('[name="ciphertext"]').val($('[name="desc"]').val())
      })
      $("#copyPass").click(function () {
        copyText(window._password)
      })
    })

    // 复制文本内容
    function copyText(text) {
      if (!text.trim()) return;
      let inputDom = document.createElement('textarea');  // 创建一个textarea元素，使用input元素的话，换行会没有了
      inputDom.setAttribute('readonly', 'readonly'); // 防止手机上弹出软键盘
      inputDom.value = text.trim(); // 给input元素赋值
      document.body.appendChild(inputDom); // 添加到body
      inputDom.select(); //选中input元素的内容
      document.execCommand('Copy'); // 执行浏览器复制命令
      inputDom.style.display = 'none';
      inputDom.remove(); // 移除input元素
    }

    // 定时刷新，避免泄露账户信息
    let reloadTime = rt = 60 * 30
    let r = document.getElementById('reload');
    setInterval(() => {
      if (--reloadTime < 0) { location.reload(); reloadTime = rt }
      r.innerText = `${Math.floor(reloadTime / 60)}分${reloadTime % 60}秒后清空输入，是否重置计时？`
    }, 1000);
    r.onclick = function () { reloadTime = rt; r.innerText = '已重置' }

  </script>

</body>

</html>